<?php

error_reporting(1);
$link = null;
$directory = "modelo/";

if(!is_dir($directory)){
    mkdir($directory);
}
/////CONEXION BD
if($link = mysql_connect("localhost", "root", "")) {
    if (!mysql_select_db("g2u", $link)){
        die ("la base de datos no existe.");
    }
} else {
   die ("error al conectar al motor."); 
}


/////OBTENEMOS LAS TABLAS DESDE BD
$rs = null;
$fila = null;
$rs = mysql_query("SHOW TABLES;", $link);
$tables = array();
if (is_resource($rs)){
    
    while($fila = mysql_fetch_array($rs)){
        $tables[]= $fila[0];
    }
    
} else {
    die ("LA BD NO TIENE TABLAS");
}



foreach ($tables as $key => $value) {
    $rs = null;
    $fila = null;
    $deleteByUpdate = false;
    $fieldStatus = null;
    $stringCampos = "";
    $fieldDesc = "";
    $statusIndex = "";
    
    $rs = mysql_query("DESC $value;", $link);
    $campos = array();

    while($fila = mysql_fetch_array($rs)){
        $campos[]= $fila[0];
        $stringCampos .= " $fila[0],"; 
        
        if(strpos($fila[0], "status")){
            $deleteByUpdate = true;
            $fieldStatus = $fila[0];
            $statusIndex = count($campos)-1;
            $statusIndex = $fila[0];
        }
        
        if(strpos($fila[0], "desc")){
            $fieldDesc = $fila[0];            
        }
    }
    
    $stringCampos = substr($stringCampos, 0, strlen($stringCampos)-1);
    
/////CREANDO ARCHIVOS DE CLASE 
    $file = $directory."modelo.$value.php";
    $fp = fopen($file, 'w');
    echo date('Y-m-d H:i:s')."  ::  Create File:".$file;
    fwrite($fp, 
"<?php
class $value { ");

$stringAtributos = "";

/////ESCRIBIENDO VARIABLES
foreach ($campos as $k => $v) {
fwrite($fp,
"
    var $".$v.";");
if ($k == 0) {
    $stringAtributos .= 'NULL,'; 
} else {
    $stringAtributos .= ' \'$this->'.$v."',"; 
}
}
fwrite($fp,
"

"); 
$stringAtributos = substr($stringAtributos, 0, strlen($stringAtributos)-1);

/*
/////CREAR FUNCION DELETE
if ($deleteByUpdate) {
/////CAMBIAR DE ESTADO
fwrite($fp, 
'
    function Delete(){
        
        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();
        $q = " select '.$fieldStatus.' from '.$value.' where '.$campos[0].' =\'".$this->'.$campos[0].'."\' " ;
        $rse = $DB->ObtenerData($q);   
        
        if($rse[0]["'.$fieldStatus.'"]==0){
            $this->'.$fieldStatus.' = 1;
        }else{
            $this->'.$fieldStatus.' = 0;
        }
        
        $query = " UPDATE estado SET
                     '.$fieldStatus.'=\'".$this->'.$fieldStatus.'."\'
                     where '.$campos[0].' =\'".$this->'.$campos[0].'."\' " ;
        
        $rs = $DB->EjecutarQuery($query);        
        $DB->DesconectarBD();        
        return $rs;  
    }
');
} else {
/////ELIMNAR EL REGISTRO
fwrite($fp, 
'
    function Delete(){

        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();

        $q = " delete  from '.$value.' where '.$campos[0].' =\'".$this->'.$campos[0].'."\' " ;
        $rs = $DB->EjecutarQuery($q);

        $DB->DesconectarBD();
        return $rs;
    }
');    
}


/////FUNCION UPDATE
fwrite($fp, 
'
    function Update(){
        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();
        
        $query = " " ;
        
        $rs = $DB->EjecutarQuery($query);        
        $DB->DesconectarBD();        
        return $rs;  
    }
');  


/////FUNCION GETDATA
fwrite($fp, 
'
    function GetData(){
        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();
         
        $query = " Select * from '.$value.' where '.$campos[0].' =\'".$this->'.$campos[0].'."\' ";
        $rs = $DB->ObtenerData($query, "'.$value.'" );

');

foreach ($campos as $k => $v) {
fwrite($fp,
'        $this->'.$v.' = $rs[0]["'.$v.'"];
');
}

fwrite($fp,
'
        $DB->DesconectarBD();        
    }
'); 


/////FUNCION SAVE
fwrite($fp, 
'
    function Save(){
        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();
        $query = " INSERT INTO '.$value.' (
                    '.$stringCampos.')
                    VALUES ('.$stringAtributos.');" ;
        
        $rs = $DB->EjecutarQuery($query);        
        $DB->DesconectarBD();        
        return $rs;        
    }
');


/////FUNCION GETLIST
fwrite($fp, 
'    
    function GetList($vals = false, $orderby = false, $lim= false){
        include_once \'recursos/conexionMysql.php\';
        $DB = new conexionMysql();
        $DB->ConectarBD();
        
        if ($_REQUEST["seccion"] == "'.  str_replace("_", "", $value).'" ) { //modulo '.$value.'
        
            if(!isset($_REQUEST["li"])){
                $li = 0;
            }else{
                $li = $_REQUEST["li"];
            }               

            if(isset($_REQUEST["page"])){
                $li = ($_REQUEST["page"]* $_SESSION[\'PREF\'][\'LIST_LIMIT\'])- $_SESSION[\'PREF\'][\'LIST_LIMIT\'];
            }

            if(!$vals){
                $vals = " * ";            
            }

            if(!$lim){
                $limit ="LIMIT ".$li.", ".$_SESSION[\'PREF\'][\'LIST_LIMIT\']." ";
            }

            if($orderby){            
                $order =" ORDER BY $orderby ";
            }else{
                $order =" ORDER BY '.$campos[count($campos)-1].' desc, '.$fieldDesc.' asc ";
            }

            if(isset($_REQUEST["estado"]) && $_REQUEST["estado"] <> 99 ){ 
                $where .= " and '.$fieldStatus.' = ".$_REQUEST["estado"]."  ";
            }   

            if($_REQUEST["filtro"]){
                $query = " Select $vals from '.$value.' where '.$fieldDesc.' like \'%".$_REQUEST["filtro"]."%\' $where
                                $order  $limit ";
            }else{
                $query = " Select $vals from '.$value.' where 1=1 $where   $order  $limit   ";
            }
            
        } else {  //desde fuera del MODULO '.strtoupper($value).'
            
             $query = " Select $vals from '.$value.' where '.$fieldStatus.' = 1 $where  ";
            
        }
        
        $rs = $DB->ObtenerData($query, "'.$value.'");

        if (trim($vals) != "count(*)"){

            foreach ($rs as $key => $val) {
                $'.substr($value, 0, 1).' = new '.$value.'();
');

foreach ($campos as $k => $v) {
fwrite($fp,
'                $'.substr($value, 0, 1).'->set_'.$v.'($val["'.$v.'"]);
');
}

fwrite($fp,
'                $rs2[] = $'.substr($value, 0, 1).';
            }

            $rs = $rs2;

            include_once \'recursos/funciones.php\';
            $e = getEstado();        
            if(is_array($rs)){
                foreach ($rs as $key => $value) {
                    if ($value["'.$statusIndex.'"] == 1) {
                        $rs[$key]["'.$statusIndex.'"] = "<img src=\'images/png/estado_habilitado.png\' />".$e[$value["'.$statusIndex.'"]];
                    } else {
                        $rs[$key]["'.$statusIndex.'"] = "<img src=\'images/png/estado_deshabilitado.png\' />".$e[$value["'.$statusIndex.'"]];
                    }  
                }
            }
        }
        $DB->DesconectarBD();      
        return $rs;                
    }
');
*/

/////GETTERS & SETTERS
foreach ($campos as $k => $v) {
fwrite($fp, 
'
    function get_'.$v.'(){
        return $this->'.$v.';
    }
    function set_'.$v.'($val){
        $this->'.$v.' = $val;
    }
');      
}



/////CERRAR CLASE
fwrite($fp, 
"
}");         
     
    fclose($fp);
    echo " <br/>";
    echo date('Y-m-d H:i:s')."  ::  End creation File:".$file;
    echo " <br/><br/>";
}